package com.donghaiair.framework.common.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 发送短信工具类
 */
@Component
public class SmsUtils {
	private static final Logger log = LoggerFactory.getLogger(SmsUtils.class);

	@Autowired
	private SmsConfigUtils config;

	/**
	 * 
	 * @param mobilePhone
	 * @param msgCoutent
	 * @return map key 0成功 1 失败
	 */
	public Map<String, String> sendMsg(String mobilePhone, String msgCoutent) {
		Map<String, String> map = new HashMap<>();
		StringBuffer sb = new StringBuffer("");
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		sb.append("<soap:Envelope " + "xmlns:api='http://demo.ls.com/' "
				+ "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
				+ "xmlns:xsd='http://www.w3.org/2001/XMLSchema' "
				+ "xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
		sb.append("<soap:Body>");
		sb.append("<MongateCsSpSendSmsNew " + "xmlns='http://tempuri.org/'>");
		sb.append("<userId>" + config.getSmsUserId() + "</userId>");
		sb.append("<password>" + config.getSmsPassword() + "</password>");
		sb.append("<pszMobis>" + mobilePhone + "</pszMobis>");
		sb.append("<pszMsg>" + msgCoutent + "</pszMsg>");
		sb.append("</MongateCsSpSendSmsNew>");
		sb.append("</soap:Body>");
		sb.append("</soap:Envelope>");
		String soapRequestData = sb.toString();
		try {
			PostMethod postMethod = new PostMethod(config.getSmsSendUrl());
			byte[] b = soapRequestData.getBytes("utf-8");
			InputStream is = new ByteArrayInputStream(b, 0, b.length);
			RequestEntity re = new InputStreamRequestEntity(is, b.length, "application/soap+xml; charset=utf-8");
			postMethod.setRequestEntity(re);
			HttpClient httpClient = new HttpClient();
			int statusCode = httpClient.executeMethod(postMethod);
			// 200说明正常返回数据
			if (statusCode == 200) {
				map.put("result", EnumConstantResult.SMS_SUCCESS);
			}
			soapRequestData = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			map.put("result", EnumConstantResult.SMS_FAIL);
			log.error("SMS send fail:" + e.getMessage());
		}
		return map;
	}

}
